<?php 
/*
数据库操作类
 */
class Model
{	
	private $link = null; // 连接表示
	private $tabName = null; //表名
	private $fields = []; //字段列表
	private $pk = null;  // 主键
	private $keys = null; // 要查询的指定字段
	private $where = null;//查询条件
	private $order = null;//排序条件
	private $limit = null;//分页条件


	//创建一个静态属性来保存对象
	//private static $obj;
	//定义一个构造函数用于初始化
	public function __construct($tabName)
	{
		$this->link = mysqli_connect(HOST , USER ,PWD , DB);
					  mysqli_set_charset($this->link ,CHAR);
		$this->tabName = $tabName;
		$this->getField();//取得表结构

	}
	// public static function getinstance($tabName)
	// {
	// 	if (self::$obj === null) {
	// 		self::$obj = new self($tabName);
	// 	}
	// 	return self::$obj;
	// }
	//查询
	public function select()
	   {
	       $keys = '*';//默认查全部
	       //判断有无字段条件值
	       if (!empty($this->keys)) {
	           $keys = $this->keys;
	           $this->keys = null;//每次用完 要清空
	       }

	       $where = '';//默认无条件
	       //判断有无
	       if (!empty($this->where)) {
	           $where = 'where '.$this->where;
	           $this->where = null;//每次用完 要清空
	       }

	       $order = '';//默认无条件
	       //判断有无
	       if (!empty($this->order)) {
	           $order = 'order by '.$this->order;
	           $this->order = null;//每次用完 要清空
	       }

	       $limit = '';//默认无条件
	       //判断有无
	       if (!empty($this->limit)) {
	           $limit = 'limit '.$this->limit;
	           $this->limit = null;//每次用完 要清空
	       }

	       //SQL
	       $sql = "select {$keys} from {$this->tabName} {$where} {$order} {$limit}";
	       return $this->query($sql);
	   }

	public function where($where)
	{
		//对象链操作
		$this->where = $where;
		return $this;
	}
	public function order($order)
	{
		$this->order = $order;
		return $this;//对象链
	}
	public function limit($limit)
	{
		$this->limit = $limit;
		return $this;
	}
	//指定字段查询
	public function  field($arr)
	{
		//如果传递来的不是数组 则返回对象自己
		if (!is_array($arr)) {
			return $this;
		}
		//如果传递来的数组 有非字段里的数据 要剔除
		foreach ($arr as $key => $val) {
			if (!in_array($val , $this->fields)) {
				unset($arr[$key]);
			}
		}
		//如果传过来的数据都被踢除了 则数组为空了
		if (empty($arr)) {
			return $this;
		}
		$this->keys =  implode(',' , $arr);
		return $this;

	}
	//查询单挑语句
	public function  find($findvalue , $findkey = null)
	{	
		if ($findkey == null) {
			$findkey = $this->pk;
		}

		$keys = '*' ;//默认查询全部字段
		if (!empty($this->keys)) {
			$keys = $this->keys;
			$this->keys = null; //每次用完清空
		}
		$sql = "select {$keys} from {$this->tabName} where {$findkey}= '{$findvalue}' limit 1";
		$data = $this->query($sql);
		//查询一条 结果是个二维数组 可以转成一维数组
		if (!empty($data)) {
			return $data[0];
		} else {
			return false;
		}
	}

	//增
	public function insert($data = [])
	{
		//判断赋值 如果data为空则取得POST中的数据
		if (empty($data)) {
			$data = $_POST;
		}

		//表单提交过来的数据会有多个,可能包含user这个数据库里字段没有的数据
		//所以要进行筛选将 字段 保留下来其他的剔除
		foreach ($data as $k => $v) {
			if (in_array($k ,$this->fields)) {
				$list[$k] = $v;
			}

		}
		$keys = implode(',', array_keys($list));
		$values = implode("','", array_values($list));
		$sql ="insert into {$this->tabName} ($keys) values ('$values')";
		//var_dump($sql);
		//echo $this->excute($sql);
		return $this->excute($sql);
	}

	//统计数据条目
	public function count()
	{
		$where = '';//默认为空
		if (!empty($this->where)) {
			$where ='where '.$this->where;
			$this->where = null;
		}
		$sql = "select count(*) as totle from {$this->tabName} {$where} ";
		//返回结果为一个二维数组
		$totle = $this->query($sql);
		return $totle[0]['totle'];
	}
	/**
	 * [count 统计共有多少条数据]
	 * @return [type] [description]
	 */
	// public function count()
	// {
	// 	$sql = "select * from {$this->tabName}";
	// 	$list = $this->query($sql);
	// 	$list = count($list);
	// 	return $list;
	// }

	//删
	public function delete($delvalue , $delkey= null)
	{	
		//如果没穿字段名则默认为主键
		if ($delkey == null) {
			$delkey = $this->pk;
		}
		$sql = "delete from {$this->tabName} where {$delkey} = {$delvalue} ";
		
		return $this->excute($sql);
	}

	//改
	public function update($date = [])
	{

		//接受数据 如果data为空则取得post传过来的数据
		
		if (empty($data)) {
			$data = $_POST;
		}
		//筛选post数据
		foreach ($data as $k => $v) {
			//如果post中的$k 在字段列表中则保留 且 不保留主键
			if (in_array($k , $this->fields) && $k != $this->pk) {
				$list[] ="`{$k}`= '{$v}' ";
			}
		}
		$set = implode(',',$list);
		$sql = "update {$this->tabName} set {$set} where {$this->pk} = {$data[$this->pk]}";
		//var_dump($sql);
		return $this->excute($sql);
	}








	//-------------------------------私有方法
	//-------------------------------私有方法
	//-------------------------------私有方法
	//专门用于查询
	private function query($sql)
	   {
	       //执行SQL
	       $result = mysqli_query($this->link, $sql);
	       //判断 执行结果
	       if ($result && mysqli_num_rows($result) > 0) {
	           $list = [];
	           $list = mysqli_fetch_all($result, MYSQLI_ASSOC);
	           return $list; //返回查询到的数据,二维数组
	       } else {
	           return false; //查询失败,返回false
	       }
	   }


	
	//专门用增删改
	private function excute($sql)
	{
		$result = mysqli_query($this->link , $sql);
		//判断结果

		if ($result && mysqli_affected_rows($this->link) > 0 ) {
			if ( mysqli_insert_id($this->link) > 0 ) {
				//返回自增id
				
			
				return mysqli_insert_id($this->link) ;
				 
			} else {
				//删改成功
				return true;
			}
		} else {
			//操作失败 返回false
			return false;
		}

	}

	//获取表结构
	 private function getField()
	    {
	        //查询表结构
	        $sql = "desc {$this->tabName}";
	        $list = $this->query($sql);
	        $fields = [];
	        foreach ($list as $val) {
	            $fields[] = $val['Field'];
	            if ($val['Key'] == 'PRI') {
	            	$this->pk = $val['Field'];
	            }
	           
	        }
	        // var_dump($list);
	        //给属性赋值
	        $this->fields = $fields;
	    }

	}